package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.annotation.CacheFind;
import com.jt.mapper.ItemCatMapper;
import com.jt.pojo.ItemCat;
import com.jt.utils.ObjectMapperUtil;
import com.jt.vo.EasyUITree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.ShardedJedis;

import java.util.ArrayList;
import java.util.List;

@Service
public class ItemCatServiceImpl implements ItemCatService{
    @Autowired
    private ItemCatMapper itemCatMapper;
    @Autowired(required = false)
    private JedisCluster jedis;
    @Override
    public String findItemCatNameById(long itemCatId) {
        return itemCatMapper.selectById(itemCatId).getName();
    }
    @CacheFind(preKey = "ITEMCAT_PARENTID")
    @Override
    public List<EasyUITree> findItemCatList(Long parentId) {
        List<EasyUITree> treeList = new ArrayList<>();

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id", parentId);
        List<ItemCat> catList = itemCatMapper.selectList(queryWrapper);

        for (ItemCat itemCat : catList) {
            long id = itemCat.getId();
            String text = itemCat.getName();
            String state = itemCat.getIsParent() ? "closed" : "open";
            EasyUITree easyUITree = new EasyUITree(id, text, state);
            treeList.add(easyUITree);
        }
        return treeList;
    }

    @Override
    public List<EasyUITree> findItemCatCache(Long parentId) {
        List<EasyUITree> treeList = new ArrayList<>();
        String key = "ITEMCAT_PARENTID::" + parentId;
        if (jedis.exists(key)) {
            String json = jedis.get(key);
            return ObjectMapperUtil.toObject(json, treeList.getClass());
        } else {
            treeList = findItemCatList(parentId);
            String json = ObjectMapperUtil.toJson(treeList);
            jedis.set(key, json);
        }
        return treeList;
    }
}
